package top.ninwoo.utils.util.impl;

import top.ninwoo.utils.util.LinuxCtlUtils;
import top.ninwoo.utils.util.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Author joliu
 * @Description
 * @Date　Create in 下午9:28 2019/10/20
 */
@Utils
public class LinuxCtlUtilsImpl implements LinuxCtlUtils {
    @Override
    // TODO: 这个函数中的异常处理是一个问题
    public String runCmd(String cmd) {
        String result = "";
        try {
            Process exec = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
            exec.waitFor();
            InputStream in = exec.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String msg;
            while((msg = br.readLine())!= null && msg.length() > 0) {
                result += msg + "\n";
            }

            if("".equals(result)) {
                // 构建Error
                InputStream errorStream = exec.getErrorStream();
                BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream));
                String eMsg;
                while((eMsg = ebr.readLine())!= null && eMsg.length() > 0) {
                    result += eMsg + "\n";
                }
                if(result.equals("")) {
                    return result;
                }
                result = "Error: " + result;
            }
            if(result.length() > 0) {
                result = result.substring(0, result.length()-1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}
